跳到主要内容

Modules

1. 前言

本节我们将介绍如何将 store 中的数据按模块划分。在复杂的大型项目中,如果将所有的数据都存在一个 state 对象中,那将使得 store 对象变得非常大,难于管理。这时候,使用 module 将变得异常重要。Modules 并非难点,接下来我们就一步步介绍 modules 的使用。

2. 如何使用

2.1 基本用法

Module 其实是一个对象,它和我们 new Vuex.Store ({…}) 传入的对象格式相同。例如:

const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态


2.2 模块的局部状态

对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。

const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是当前模块的局部状态
state.count++
}
},

getters: {
doubleCount (state) {
// 这里的 `state` 对象是当前模块的局部状态
return state.count \* 2
}
}
}

同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

const moduleA = {
// ...
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}

完整示例: